const ble = require("../../utils/bluetooth");
const util = require("../../utils/util");
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sanyuan : true,
    tieli : false,
    nadian : false,
    qita : false,
    param_list : [
      ["预充预防使能", "", "", false, 2088, 1],
      ["预充启动电压_mV", "", "", false, 2089, 1],
      ["充电管保护电流_mA", "", "", false, 2092, 1],
      ["静止电流阈值_mA", "", "", false, 2093, 1],
      ["SOC 低电量告警使能", "", "", false, 4425, 1],
      ["SOC 系统告警_%", "", "", false, 4426, 1],
      ["SOC LV3告警_%", "", "", false, 4427, 1],
      ["SOC 解除告警_%", "", "", false, 4428, 1],
    ],
    modify_list : []
  },

  onLoad(options) {
    if (ble.isConncted()) {
      this.readData()
    }
  },

  async readData() {
    const { params } = await ble.getParamsWrapper(false)

    this.setData({
      param_list : params
    })
  },

  changeContent(e) {
    const index = e.currentTarget.dataset.index; 
    const value =  e.detail.value;
    this.data.param_list[index][2] = value
    this.addModifyList({
      address : e.currentTarget.dataset.address,
      value : value * e.currentTarget.dataset.ratio
    })
  },

  addModifyList(e) {
    var b_exists = false

    for (let i = 0; i < this.data.modify_list.length; i++) {
      const element = this.data.modify_list[i];
      if (element.address == e.address) {
        element.value = e.value
        b_exists = true
      }
    }

    if (!b_exists) {
      this.data.modify_list.push({
        address : e.address,
        value : e.value
      })
    }
  },

  async save() {
    if  (app.globalData.userInfo.current_permission < 2){
      wx.showModal({
        content: '您没有修改功能设置的权限，请前往验证二级权限密码',
      })

      return
    }
    console.log("功能开始修改啦")
    if (!ble.isConncted()) {
      return;
    }

    wx.showLoading({
      title: '保存中...',
    })
    console.log(this.data.modify_list)

    for (let i = 0; i < this.data.modify_list.length; i++) {
      const element = this.data.modify_list[i];
      let address = element.address
      let value = parseInt(element.value)
      console.log("发送地址：",address, value)
      await ble.writeValueWrapper(address, value)
      await util.sleep(500)
    }

    wx.hideLoading()
  },

  choose(e) {
    console.log(e.currentTarget.dataset.index)
    const index = parseInt(e.currentTarget.dataset.index);
    if (index == 0) {
      this.setData({sanyuan:true,tieli:false,nadian:false,qita:false})
    } else if (index == 1) {
      this.setData({sanyuan:false,tieli:true,nadian:false,qita:false})
    } else if (index == 2) {
      this.setData({sanyuan:false,tieli:false,nadian:true,qita:false})
    } else {
      this.setData({sanyuan:false,tieli:false,nadian:false,qita:true})
    }
  }
})